﻿namespace _4_NovaAdmin.Web.Core.ServiceExtensions;

/// <summary>
/// 限流服务的配置
/// </summary>
public static class IpRateLimitingSetup
{
    public static void AddIpRateLimiting(this IServiceCollection services, IConfiguration Configuration)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(Configuration);
        // 添加内存缓存（限流中间件依赖）
        services.AddMemoryCache();

        // 加载限流配置
        services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
        services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));

        // 注册限流服务
        services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
        services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
        services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
        services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
    }
}
